#include "kernel_operator.h"
using namespace AscendC;

template <typename U, typename T>
class KernelBroadCast
{

public:
    __aicore__ inline KernelBroadCast() {}
    __aicore__ inline void Init(GM_ADDR condition, GM_ADDR x1, GM_ADDR x2, GM_ADDR y,
                                int32_t y_dimensional,
                                int32_t *y_ndarray, int32_t *x0_ndarray, int32_t *x1_ndarray, int32_t *x2_ndarray,
                                int32_t *y_sumndarray, int32_t *x0_sumndarray, int32_t *x1_sumndarray, int32_t *x2_sumndarray)
    {
        ASSERT(GetBlockNum() != 0 && "block dim can not be zero!");

        this->y_dimensional = y_dimensional;

        this->y_ndarray = y_ndarray;
        this->x0_ndarray = x0_ndarray;
        this->x1_ndarray = x1_ndarray;
        this->x2_ndarray = x2_ndarray;
        this->y_sumndarray = y_sumndarray;
        this->x0_sumndarray = x0_sumndarray;
        this->x1_sumndarray = x1_sumndarray;
        this->x2_sumndarray = x2_sumndarray;

        x1Gm.SetGlobalBuffer((__gm__ T *)x1, 1);
        x2Gm.SetGlobalBuffer((__gm__ T *)x2, 1);
        conditionGm.SetGlobalBuffer((__gm__ U *)condition, 1);
        yGm.SetGlobalBuffer((__gm__ T *)y, 1);
    }
    __aicore__ inline void Process()
    {
        int dim = this->y_dimensional;

        for (int j = 0; j < this->y_sumndarray[dim]; j++)
        {
            int x0_start = 0, x1_start = 0, x2_start = 0;
            for (int k = 0; k < dim; k++)
            {

                if (this->x0_ndarray[k] != 1)
                {
                    x0_start += this->x0_sumndarray[k] * (j / this->y_sumndarray[k] % this->y_ndarray[k]);
                }
                if (this->x1_ndarray[k] != 1)
                {
                    x1_start += this->x1_sumndarray[k] * (j / this->y_sumndarray[k] % this->y_ndarray[k]);
                }
                if (this->x2_ndarray[k] != 1)
                {
                    x2_start += this->x2_sumndarray[k] * (j / this->y_sumndarray[k] % this->y_ndarray[k]);
                }
            }
            
            T x1 = x1Gm.GetValue(x1_start);
            T x2 = x2Gm.GetValue(x2_start);
            U is = conditionGm.GetValue(x0_start);
            yGm.SetValue(j, is ? x1 : x2);
        }
    }

private:
    GlobalTensor<U> conditionGm;
    GlobalTensor<T> x1Gm;
    GlobalTensor<T> x2Gm;
    GlobalTensor<T> yGm;

    int32_t y_dimensional;
    int32_t *y_ndarray;
    int32_t *x0_ndarray;
    int32_t *x1_ndarray;
    int32_t *x2_ndarray;

    int32_t *y_sumndarray;
    int32_t *x0_sumndarray;
    int32_t *x1_sumndarray;
    int32_t *x2_sumndarray;
};